package com.zk.mockito.cases;

import org.junit.Assert;
import org.junit.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class Case010_StubbingConsecutiveCalls {



    @Test
    public void testStubbingConsecutiveCalls() {
        Mocked mock = mock(Mocked.class);

        when(mock.someMethod("some arg"))
                .thenThrow(new RuntimeException())
                .thenReturn("foo");

        //First call: throws runtime exception:
        Assert.assertThrows(RuntimeException.class, () -> mock.someMethod("some arg"));

        //Second call: prints "foo"
        System.out.println(mock.someMethod("some arg"));

        //Any consecutive call: prints "foo" as well (last stubbing wins).
        System.out.println(mock.someMethod("some arg"));
    }

    /**
     *  简洁的多次调用存根方法
     */
    @Test
    public void testStubbingConsecutiveCallsShort() {
        Mocked mock = mock(Mocked.class);

        // 较短版本的连续存根
        // Alternative, shorter version of consecutive stubbing:
        when(mock.someMethod("some arg"))
                .thenReturn("one", "two", "three");

        //First call: throws runtime exception:
        Assert.assertThrows(RuntimeException.class, () -> mock.someMethod("some arg"));

        //Second call: prints "foo"
        System.out.println(mock.someMethod("some arg"));

        //Any consecutive call: prints "foo" as well (last stubbing wins).
        System.out.println(mock.someMethod("some arg"));

    }

    /**
     * Override ，多次调用存根，会覆盖之前的操作
     */
    @Test
    public void testStubbingConsecutiveCallsOverride() {
        Mocked mock = mock(Mocked.class);

        // override: 多次调用会覆盖
        //All mock.someMethod("some arg") calls will return "two"
        when(mock.someMethod("some arg"))
                .thenReturn("one");
        when(mock.someMethod("some arg"))
                .thenReturn("two");

        //First call: throws runtime exception:
        Assert.assertThrows(RuntimeException.class, () -> mock.someMethod("some arg"));

        //Second call: prints "foo"
        System.out.println(mock.someMethod("some arg"));

        //Any consecutive call: prints "foo" as well (last stubbing wins).
        System.out.println(mock.someMethod("some arg"));
    }

}
